package com.vivo.tasks.vivofx;

import com.thinkgem.jeesite.common.persistence.Page;
import com.vivo.common.DatabaseContextHolder;
import com.vivo.dealer.entity.ViDeaWarehousesnquery;
import com.vivo.dealer.service.ViDeaWarehousesnqueryService;
import com.vivo.fx.dealer.entity.FxDeaWarehousesnquery;
import com.vivo.fx.dealer.service.FxDeaWarehousesnqueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class TaskDeaWarehouseSnQuery {

    @Autowired
    private FxDeaWarehousesnqueryService fxDeaWarehousesnqueryService;

    @Autowired
    private ViDeaWarehousesnqueryService viDeaWarehousesnqueryService;

    public void SyncData() {
        syncLastData("ah");
        syncLastData("js");
    }


    private void syncLastData(String area) {
        System.out.println("get ware house query sn info from " + area + " start ...");

        Calendar cal = Calendar.getInstance();
        Date startDate = null;
        Date endDate = new Date();

        ViDeaWarehousesnquery lastItem = new ViDeaWarehousesnquery();
        lastItem.setTableZone(area);
        lastItem = viDeaWarehousesnqueryService.getLastChangeItem(lastItem);

        if (lastItem == null) {
        } else {
            startDate = lastItem.getLastchangedate();
            System.out.println("last change date is :" + startDate);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        int pageStart = 1;
        int pageSize = 5000;
        Page<FxDeaWarehousesnquery> page = new Page<FxDeaWarehousesnquery>(pageStart, pageSize);
        FxDeaWarehousesnquery fxDeaWarehousesnquery = new FxDeaWarehousesnquery();
        fxDeaWarehousesnquery.setBeginLastchangedate(startDate);
        fxDeaWarehousesnquery.setEndLastchangedate(endDate);

        // 添加当前整点时间
        fxDeaWarehousesnquery.setZdTime(sdf.format(new Date()));

        page.setOrderBy("a.lastchangedate");

        try {
            Helper.changeDB(area);
            Page<FxDeaWarehousesnquery> pageRes = fxDeaWarehousesnqueryService.findPage(page, fxDeaWarehousesnquery);
            DatabaseContextHolder.setMainDb();
            System.out.println("cur page is :" + pageRes.getPageNo() + " and pageSize is :" + pageRes.getPageSize());

            saveSnQueryList(pageRes.getList(), area);

            for (int i = pageStart + 1; i <= pageRes.getTotalPage(); i++) {
                page.setPageNo(i);

                Helper.changeDB(area);
                pageRes = fxDeaWarehousesnqueryService.findPage(page, fxDeaWarehousesnquery);
                DatabaseContextHolder.setMainDb();
                System.out.println("cur page is :" + pageRes.getPageNo() + " and pageSize is :" + pageRes.getPageSize());

                saveSnQueryList(pageRes.getList(), area);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DatabaseContextHolder.setMainDb();
        }

        System.out.println("get ware house query sn info from " + area + " end!");
    }

    private void saveSnQueryList(List<FxDeaWarehousesnquery> queryList, String area) {
        List<ViDeaWarehousesnquery> vdqList = new ArrayList<ViDeaWarehousesnquery>();

        for (FxDeaWarehousesnquery fxQ: queryList) {
            if(fxQ.getSnnumber() == null || fxQ.getSnnumber().length() != 15) {
                continue;
            }

            ViDeaWarehousesnquery vdq = new ViDeaWarehousesnquery();
            vdq.setTableZone(area);

            vdq.setId(fxQ.getSnnumber());
            vdq.setIsTaskInsert(true);
            vdq.setSnid(fxQ.getSnid());
            vdq.setBoxnumber(fxQ.getBoxnumber());
            vdq.setCurrentwarehouseid(fxQ.getCurrentwarehouseid());
            vdq.setWaresid(fxQ.getWaresid());
            vdq.setSnstate(fxQ.getSnstate());
            vdq.setLastchangedate(fxQ.getLastchangedate());
            vdq.setIsmodelmachine(fxQ.getIsmodelmachine());
            vdq.setIsbadmachine(fxQ.getIsbadmachine());
            vdq.setMeid(fxQ.getMeid());
            vdq.setImei2(fxQ.getImei2());
            vdq.setBacksourcewarehouseid(fxQ.getBacksourcewarehouseid());
            vdq.setProtouseemployeeid(fxQ.getProtouseemployeeid());
            vdq.setInwarehousedate(fxQ.getInwarehousedate());
            vdq.setInwarehouseid(fxQ.getInwarehouseid());
            vdq.setLastretaildate(fxQ.getLastretaildate());
            vdq.setLastretailhandleremployeeid(fxQ.getLastretailhandleremployeeid());
            vdq.setElectronicregistrytime(fxQ.getElectronicregistrytime());
            vdq.setLastdispatchdate(fxQ.getLastdispatchdate());

            vdqList.add(vdq);

            // 批量添加数据
            if (vdqList.size() >= 1000) {
                try {
                    viDeaWarehousesnqueryService.insertByBatch(vdqList, area);
                } catch (Exception e) {
                    // 发生异常，需要每个进行操作
                    saveListAfterError(vdqList);
                }

                // 保存成功后清空操作
                vdqList.clear();
            }
        }


        // 检查列表是否为空
        if(vdqList.size() > 0) {
            try {
                viDeaWarehousesnqueryService.insertByBatch(vdqList, area);
            } catch (Exception e) {
                // 发生异常，需要每个进行操作
                saveListAfterError(vdqList);
            }

            // 保存成功后清空操作
            vdqList.clear();
        }
    }


    public void saveListAfterError(List<ViDeaWarehousesnquery> viDeaWarehousesnqueries) {
        for (ViDeaWarehousesnquery vdq : viDeaWarehousesnqueries) {
            try {
                viDeaWarehousesnqueryService.save(vdq);
            } catch (Exception e) {
                ViDeaWarehousesnquery newVdq = new ViDeaWarehousesnquery();
                String sn = vdq.getId();
                String area = vdq.getTableZone();

                newVdq.setTableZone(area);
                newVdq.setId(sn);
                newVdq = viDeaWarehousesnqueryService.get(vdq);
                // 已经存在，需要进行更新即可
                if (newVdq != null) {
                    System.out.println("数据已经存在：" + vdq.getId());

                    vdq.setIsTaskInsert(false);
                    vdq.setIsNewRecord(false);

                    viDeaWarehousesnqueryService.save(vdq);
                } else {
                    System.out.println("数据保存失败：" + sn);
                    e.printStackTrace();
                }
            }

        }
    }


    public void updZd(String area) {

    }
}
